<script setup lang="ts">
import { ref, onMounted, onUnmounted, inject } from 'vue'
import { storeToRefs } from 'pinia'
import { useProjectStore } from '../stores/store'

// 正确注入setTaskBar函数
const setTaskBar = inject('setTaskBar') as ((text: string, progress?: number) => void)
const printToTerm = inject('printToTerm') as ((text: string, lvl?: string) => void)

const store = useProjectStore()
const { settings } = storeToRefs(store)

declare global {
  interface Window {
    pywebview: { api: any },
    debug: (text: string, type: any) => void
  }
}

// 添加用于显示图片的响应式变量
const imageData = ref('')

// 加载设置


const testDamo = async () => {
  try {
    await window.pywebview.api.dm_start(settings.value.WebDM.path, String(settings.value.WebDM.port))
  } catch (e) {
    printToTerm('WebDM启动失败，请手动运行WebDM.exe后重试，将忽略该错误直接连接WebDM服务')
  }
  console.log(window.pywebview.api.DM)
  const res = await window.pywebview.api.dm_reg(settings.value.dm.注册码, settings.value.dm.附加码, String(settings.value.WebDM.port))
  // 前端请求会有跨域的问题，导致无法注册，从后端注册
  if (res.suc === true) {
    setTaskBar('dm测试成功！')
    printToTerm(`dm测试成功！访问 http://localhost:${settings.value.WebDM.port}/swagger/index.html 查看接口`, 'success')
  } else {
    setTaskBar('dm测试失败！')
    printToTerm('dm测试失败！', 'info')
  }
}

const UnBindWindow = async () => {
  const res = await window.pywebview.api.UnBindWindow()
  if (res === 1) {
    setTaskBar('WebDM解绑窗口成功！')
    printToTerm('WebDM解绑窗口成功！', 'success')
  } else {
    setTaskBar('WebDM解绑窗口失败！')
    printToTerm('WebDM解绑窗口失败！', 'warn')
  }
}

const setQSExchangeAppPath = async () => {
  const res = await window.pywebview.api.select_file()
  if (res) {
    store.updateSettingsField(['game', 'path'], res)
  }
}

const setDmPath = async () => {
  const res = await window.pywebview.api.select_file()
  if (res) {
    store.updateSettingsField(['WebDM', 'path'], res)
  }
}

const download = async (name: string) => {
  if (name === 'WebDM') {
    const res = await window.pywebview.api.download_app(name, { currentPath: settings.value.WebDM.path })
    store.updateSettingsField(['WebDM', 'path'], res.path)
  } else {
    const res = await window.pywebview.api.download_app(name, { currentPath: settings.value.game.path })
    store.updateSettingsField(['game', 'path'], res.path)
  }
}

// 添加证券账户登录和注销功能
const loginAccount = async () => {
  try {
    // 调用Python端的登录功能
    const result = await window.pywebview.api.login_account({
      broker: settings.value.game.名称,
      account: settings.value.game.账号,
      password: settings.value.game.密码,
      appPath: settings.value.game.path
    })

    if (result.success) {
      setTaskBar('登录成功')
      printToTerm('登录成功', 'success')
    } else {
      alert(`登录失败：${result.msg}`)
    }
  } catch (error) {
    console.error('登录过程中出现错误:', error)
    printToTerm(`登录过程中出现错误，请查看控制台获取更多信息，${error}`)
    alert('登录过程中出现错误，请查看控制台获取更多信息')
  }
}

const logoutAccount = async () => {
  try {
    // 调用Python端的注销功能
    const result = await window.pywebview.api.logout_account({
      broker: settings.value.game.名称,
      account: settings.value.game.账号
    })

    if (result.success) {
      alert('注销成功！')
    } else {
      alert(`注销失败：${result.message}`)
    }
  } catch (error) {
    console.error('注销过程中出现错误:', error)
    printToTerm(`注销过程中出现错误，请查看控制台获取更多信息，${error}`)
    alert('注销过程中出现错误，请查看控制台获取更多信息')
  }
}

const exitWebDM = async () => {
  try {
    await window.pywebview.api.exitWebDM(settings.value.WebDM.port)
    alert('已退出WebDM后台进程！')
  } catch (error) {
    console.error('退出WebDM后台进程时出现错误:', error)
    printToTerm(`退出WebDM后台进程时出现错误！${error}`)
    setTaskBar('退出WebDM后台进程时出现错误！')
    alert('退出WebDM后台进程时出现错误，请查看控制台获取更多信息')
  }
}

const Capture = async () => {
  const res = await window.pywebview.api.Capture()
  if (res && res.suc) {
    imageData.value = res.image
    printToTerm(`截图成功！`, 'success')
    setTaskBar('截图成功')
  } else {
    imageData.value = ''
    printToTerm(`截图失败！${JSON.stringify(res)}`, 'error')
    setTaskBar(`截图失败！`)
  }
}

onUnmounted(() => {
  store.saveSettings()
})
const testAny = async () => {
  const res = await window.pywebview.api.TurnToTextObj('甜根草')
  console.log(res)
}
</script>

<template>
  <div class="size-full p-2">
    <div>
      <button @click="testAny">测试</button>
    </div>
    <div class="w-full grid grid-cols-1 gap-2">
      <div>
        <button class="top1" @click="store.loadSettings">读取配置信息</button>
        <button class="top1" @click="store.saveSettings">保存配置信息</button>
        <button class="top1" @click="testDamo">测试dm</button>
      </div>
      <div>
        dm
        <button
          class="ml-2 text-sm bg-blue-500 hover:bg-blue-700 text-white py-1 px-2 rounded"
          @click="exitWebDM"
        >
          退出WebDM后台进程
        </button>
        <button
          class="mt-2 px-3 py-1 bg-red-500 text-white rounded hover:bg-red-600 text-sm"
          @click="UnBindWindow"
        >
          解绑当前窗口
        </button>
        <button
          class="ml-2 text-sm bg-blue-500 hover:bg-blue-700 text-white py-1 px-2 rounded"
          @click="Capture"
        >
          截图
        </button>
      </div>

      <!-- 图片显示区域 -->
      <div v-if="imageData" class="mt-2 p-2 border border-gray-300 rounded">
        <h3 class="text-lg font-medium mb-2">截图预览</h3>
        <img :src="imageData" alt="Screenshot" class="max-w-full max-h-96" />
        <button
          @click="imageData = ''"
          class="mt-2 px-3 py-1 bg-red-500 text-white rounded hover:bg-red-600 text-sm"
        >
          清除图片
        </button>
      </div>

      <div class="bg-red-100 flex">
        <div class="w-10"></div> <!-- 占位指定宽度 -->
        <div class="flex-1 bg-red-100 grid grid-cols-10 min-w-0">
          <label class="self-center font-medium text-gray-700 col-span-2">
            注册码：
          </label>
          <input type="text" class="col-span-8 bg-white border-1 px-1" v-model="settings.dm.注册码">
        </div>

      </div>
      <div class="bg-red-100 flex">
        <div class="w-10"></div> <!-- 占位指定宽度 -->
        <div class="flex-1 grid grid-cols-10">
          <label class="self-center font-medium text-gray-700 col-span-2">
            附加码：
          </label>
          <input type="text" class="col-span-8 bg-white border-1 px-1" v-model="settings.dm.附加码">
        </div>
      </div>
      <div class="bg-red-100 flex">
        <div class="w-10"></div> <!-- 占位指定宽度 -->
        <div class="flex-1 grid grid-cols-10">
          <label class="self-center font-medium text-gray-700 col-span-2">
            WebDM路径：
          </label>
          <div class="col-span-8 grid grid-cols-10">
            <input type="text" class="col-span-6 bg-white border-1 px-1" v-model="settings.WebDM.path">
            <div class="col-span-4 flex space-x-1">
              <button
                title="自动下载WebDM"
                class="flex-1 mx-1 h-full bg-red-300 hover:bg-blue-600 text-black font-medium rounded-md transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50"
                @click="download('WebDM')">下载
              </button>
              <button
                title="选择本地WebDM路径"
                class="flex-1 mx-0 h-full bg-red-300 hover:bg-blue-600 text-black font-medium rounded-md transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50"
                @click="setDmPath">选择
              </button>
            </div>

          </div>
        </div>
      </div>
      <div class="bg-red-100 flex">
        <div class="w-10"></div> <!-- 占位指定宽度 -->
        <div class="flex-1 grid grid-cols-10">
          <label class="self-center font-medium text-gray-700 col-span-2">
            WebDM服务端口：
          </label>
          <input type="text" class="col-span-8 bg-white border-1 px-1" v-model="settings.WebDM.port">
        </div>
      </div>
      <div>
        游戏账号
        <button
          class="ml-2 text-sm bg-blue-500 hover:bg-blue-700 text-white py-1 px-2 rounded"
          title="登录游戏"
          @click="loginAccount"
        >
          登录
        </button>
        <button
          class="ml-1 text-sm bg-red-500 hover:bg-red-700 text-white py-1 px-2 rounded"
          title="注销游戏"
          @click="logoutAccount"
        >
          注销
        </button>
      </div>

      <div class="bg-red-100 flex">
        <div class="w-10"></div> <!-- 占位指定宽度 -->
        <div class="flex-1 bg-red-100 grid grid-cols-10 min-w-0">
          <label class="self-center font-medium text-gray-700 col-span-2">
            game名：
          </label>
          <select
            id="broker"
            v-model="settings.game.名称"
            class="col-span-8 block w-full bg-white border border-black px-2 shadow"
          >
            <option value="天谕" selected>天谕</option>
          </select>
        </div>
      </div>

      <div class="bg-red-100 flex">
        <div class="w-10"></div> <!-- 占位指定宽度 -->
        <div class="flex-1 grid grid-cols-10">
          <label class="self-center font-medium text-gray-700 col-span-2">
            游戏路径：
          </label>
          <div class="col-span-8 grid grid-cols-10">
            <input type="text" class="col-span-6 bg-white border-1 px-1" v-model="settings.game.path">
            <div class="col-span-4 flex space-x-4">
              <button
                title="下载游戏运行文件（需要手动安装，然后选择安装的软件）"
                class="flex-1 mx-1 h-full bg-red-300 hover:bg-blue-600 text-black font-medium rounded-md transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50"
                @click="download(settings.game.名称)">下载
              </button>
              <button
                title="选择已安装游戏软件路径"
                class="flex-1 ml-1 h-full bg-red-300 hover:bg-blue-600 text-black font-medium rounded-md transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50"
                @click="setQSExchangeAppPath">选择
              </button>
            </div>

          </div>
        </div>
      </div>


      <div class="bg-red-100 flex">
        <div class="w-10"></div> <!-- 占位指定宽度 -->
        <div class="flex-1 grid grid-cols-10">
          <label class="self-center font-medium text-gray-700 col-span-2">
            账号：
          </label>
          <input type="text" class="col-span-8 bg-white border-1 px-1" v-model="settings.game.账号">
        </div>
      </div>

      <div class="bg-red-100 flex">
        <div class="w-10"></div> <!-- 占位指定宽度 -->
        <div class="flex-1 grid grid-cols-10">
          <label class="self-center font-medium text-gray-700 col-span-2">
            密码：
          </label>
          <input type="text" class="col-span-8 bg-white border-1 px-1" v-model="settings.game.密码">
        </div>
      </div>
    </div>


  </div> <!-- 类中不能添加container，因为container是tailwindcss的默认容器类，会限制最大宽度 -->
</template>

<style scoped>
.top1 {
  background-color: #f5c6cb;
  border-radius: 5px;
  padding: 2px 20px 2px 20px;
  margin: 5px;
  width: 200px;
}

.top1:hover {
  background-color: #646cff;
}
</style>
